package org.example.codeservce.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.SneakyThrows;
import org.example.codeservce.entity.Order;
import org.example.codeservce.service.OrderService;
import org.example.codeservce.service.WebSocketService;
import org.example.codeservce.util.AlipayUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * author: Li Qing
 * date: 2024/5/17 11:19
 * description:
 */
@Service("OrderWebSocketServiceImpl")
public class OrderWebSocketServiceImpl implements WebSocketService<Order>
{

    @Resource
    private AlipayUtil alipayUtil;

    @Resource
    private OrderService orderService;

    @SneakyThrows
    @Override
    public void execute(WebSocketSession crx, Order order)
    {
        while (true)
        {
            String price = alipayUtil.selectPayPrice(order.getOrderNo());
            Thread.sleep(2000);
            if (StringUtils.isEmpty(price))
            {
                order.setStatus(0);
                crx.sendMessage(new TextMessage(JSONUtil.toJsonStr(order)));
            }
            else
            {
                order.setStatus(1);
                break;
            }
        }
        orderService.update(new LambdaUpdateWrapper<Order>()
                .eq(Order::getOrderNo, order.getOrderNo())
                .set(Order::getStatus,1));
        crx.sendMessage(new TextMessage(JSONUtil.toJsonStr(order)));
    }
}
